package com.ruoyi.web.controller.system;

import java.util.List;
import java.util.Map;

import javax.validation.constraints.NotNull;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.ProductTerminal;
import com.ruoyi.system.domain.ValidationGroups.Update;
import com.ruoyi.system.domain.vo.QueryVo;
import com.ruoyi.system.service.IProductService;
import com.ruoyi.system.service.IProductTelemetryService;
import com.ruoyi.system.service.IProductTerminalService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;

@SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
@Slf4j
@RestController
@RequestMapping("/system/product.v2")
public class ProductTerminalController extends BaseController {
    @Autowired
    IProductService productService;

    @Autowired
    IProductTerminalService productTerminalService;

    @Autowired
    IProductTelemetryService productTelemetryService;

    @Autowired
    TokenService tokenService;

    @Autowired
    ISysDeptService sysDeptService;

    private AjaxResult checkExistance(ProductTerminal productTerminal) {
        Map<String, Object> existance = productTerminalService.findExistance(productTerminal);
        if (existance != null) {
            Object name_exists = existance.get("name_exists");
            if (name_exists != null && Integer.parseInt(name_exists.toString()) > 0) { 
                return AjaxResult.error(HttpStatus.ERROR, "终端名称已经存在");
            }
            Object number_exists = existance.get("number_exists");
            if (number_exists != null && Integer.parseInt(number_exists.toString()) > 0) { 
                return AjaxResult.error(HttpStatus.ERROR, "终端序号已经存在");
            }
        }
        return null;
    }

    @PreAuthorize("@ss.hasPermi('system:product:terminal:list')")
    @GetMapping(value = "/{id}/terminals/list", produces = "application/json;charset=UTF-8")
    public Object indexTerminals(@PathVariable("id") @NotNull(message = "id不能为null") Integer id) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("product_id", id);
        queryVo.filters.put("company_id", companyId);
        startPage();
        List<ProductTerminal> productTerminals= productTerminalService.index(queryVo);
        return getDataTable(productTerminals);
    }

    @PreAuthorize("@ss.hasPermi('system:product:terminal:enum')")
    @GetMapping(value = "/{id}/terminals/enum", produces = "application/json;charset=UTF-8")
    public AjaxResult enumerateTerminals(@PathVariable("id") @NotNull(message = "id不能为null") Integer id) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("product_id", id);
        queryVo.filters.put("company_id", companyId);
        return AjaxResult.success(productTerminalService.enumerate(queryVo));
    }

    @PreAuthorize("@ss.hasPermi('system:product:terminal:query')")
    @GetMapping(value = "/terminal/{id}", produces = "application/json;charset=UTF-8")
    public AjaxResult retrieveTerminalOfProduct(@PathVariable("id") @NotNull(message = "id不能为null") Integer id) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        queryVo.filters.put("company_id", companyId);
        ProductTerminal productTerminal = productTerminalService.retrieve(queryVo);
        if (productTerminal == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        return AjaxResult.success(productTerminal);
    }

    @PreAuthorize("@ss.hasPermi('system:product:terminal:edit')")
    @Log(title = "产品终端", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/terminal/edit", produces = "application/json;charset=UTF-8")
    public AjaxResult editTerminalOfProduct(@RequestBody @Validated(Update.class) ProductTerminal productTerminal) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", productTerminal.getId());
        queryVo.filters.put("company_id", companyId);
        ProductTerminal target = productTerminalService.retrieve(queryVo);
        if (target == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        productTerminal.setProductId(target.getProductId());
        productTerminal.setNumber(target.getNumber());
        productTerminal.setTerminalId(target.getTerminalId());
        productTerminal.setCompanyId(target.getCompanyId());
        AjaxResult ret = checkExistance(productTerminal);
        if (ret != null) {
            return ret;
        }
        if (productTerminalService.update(productTerminal)) {
            return AjaxResult.success();
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }
}
